export const streamFetch = ({ url, data, onMessage, abortSignal }) => {
    return new Promise((resolve, reject) => {
        (async () => {
            try {
                const res = await fetch(url, {
                    method: 'POST',
                    headers: {
                    'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({...data,cur_env:import.meta.env.ELECTRON ? "desktop" : "pc"}),
                    ...(abortSignal?.signal ? { signal: abortSignal.signal } : {})
                });
                
                const reader = res.body?.getReader();
                if (!reader) return;
    
                const decoder = new TextDecoder();
                let responseText = '';
    
                const read = async () => {
                    try {
                        const { done, value } = await reader?.read();
    
                        if (done) {
                            if (res.status === 200) {
                                resolve({ responseText });
                            } else {
                                const parseError = JSON.parse(responseText);
                                reject(parseError?.message || '请求异常');
                            }
    
                            return;
                        }
    
                        const text = decoder.decode(value);
                        responseText += text;
                        onMessage(text);
                        read();
                    } catch (err) {
                        if (err?.message === 'The user aborted a request.') {
                            return resolve({ responseText });
                        }
                        reject(typeof err === 'string' ? err : err?.message || '请求异常');
                    }
                };
                read();
            } catch (err) {
                console.log(err, '====');
                reject(typeof err === 'string' ? err : err?.message || '请求异常');
            }               
        })()
    });
}